using LitJson;
using Sailfish;
using System.IO;
using System.Reflection;
using UnityEngine;

public class JsonMono : MonoBehaviour
{
    const string folder = "CustomJson";
    string jsonPath => $"{Application.streamingAssetsPath}/{folder}/{saveName}.json";

    public virtual string saveName
    {
        get => GetType().ToString();
    }

    void Awake()
    {
        Load();
        JsonGUIContent.AddJsonMono(this);
    }


    public void Load()
    {
        if (!File.Exists(jsonPath))
        {
            Save();
        }
        else
        {
            var jsonTxt = File.ReadAllText(jsonPath);
            var json    = JsonMapper.ToObject(jsonTxt, this.GetType());
            var fields  = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);

            foreach (var item in fields)
            {
                var value = item.GetValue(json);
                item.SetValue(this, value);
            }
        }
    }



    private void OnDestroy()
    {
        Save();
    }

    public void Save()
    {
        if (!File.Exists(jsonPath))
        {
           var dire= Path.GetDirectoryName(jsonPath);
            if (!Directory.Exists(dire))
            {
                Directory.CreateDirectory(dire);
            }
        }
        File.WriteAllText(jsonPath, JsonUtility.ToJson(this));

#if UNITY_EDITOR
        if (!Application.isPlaying)
            UnityEditor.EditorUtility.SetDirty(this.gameObject);
#endif

    }
}

